import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {header, aliyun} from '../data/config'
import {random_string, get_suffix, previewImg, imgPreviewModal} from '../data/util'

import {
  contacts as valid_name,
  price    as valid_price
} from '../data/validate'

const base = url.base,
  addOrModifyBuildinginfo = request.addOrModifyBuildinginfo,
  getProvinceList = request.getProvinceList,
  getServiceType = request.getServiceType,
  getCityList = request.getCityList,
  getDeveloperList = request.getDeveloperList,
  getPaychannelList = request.getPaychannelList,
  getInformBookTemplateList = request.getInformBookTemplateList

// 页面标题
const title = '楼盘',
  action = '添加'

let form = new Vue({
  el: '#form',
  data: () => ({
    propertyName: '',
    dId: '',
    developerName: '',
    developerList: [],
    province: '',
    provinceList: [],
    city: '',
    cityList: [],
    serviceType: '',
    serviceTypeList: [],
    otherServiceType: [],
    otherServiceTypeList: [],
    propertyAddress: '',
    picName: '',
    picMobile: '',
    channel: [],
    channelList: [],
    isView: 0,
    isQuickLock: 0,
    lockImg: '',
    islockImgLock: false,
    // 锁屏图片上传进度
    lockImgProgress: 0,
    lockImgPreview: '',
    // 超时锁定时间 默认15分钟
    lockTime: 15,
    // 超时锁定时间选择项 1-15 分钟
    lockTimeList: Array.apply(null, Array(15)).map((i, _i) => (_i + 1)),
    broker: 0,
    posSignature: 0,
    isShowName: 0,
    showBankInfo: 1,
  /*  isCheckZxbg: 0,
    isPayToDev: 0,*/
    isCreateTestType: 1,
    brokerCommModel: 1,
    brokerCommConfig: '',
    careerCounselorModel: 1,
    careerCounselorConfig: '',
    propertyArea: '',
    salePhone: '',
    longitude: '',
    latitude: '',
    openQuotationTime: '2088-12-31',
    templetId: '',
    templetIdList: [],
    printNum: 1,
    printNumList: [1, 2],
    ylTicketCount: 1,
    ylTicketCountList: [1, 2],
    isLock: true,
    isMap: false,
    // 是否签名
    isSignature: 0,
    agreement: 0
  }),
  mounted: function () {

    let that = this

    let loading = layer.msg('初始化数据中...', {
      icon: 16,
      time: 0,
      shade: .5
    })

    this.initMap()
    this.initTime()

    Promise
      .all([this.getProvinceList(), this.getDeveloper(), this.getPaychannelList(), this.getServiceTypeList(), this.getInformBookTemplateList()])
      .then((res) => {

        layer.close(loading)

        that.isLock = false

        that.provinceList = res[0].object
        that.developerList = res[1].object
        that.channelList = res[2].object
        that.serviceTypeList = res[3].object
        that.templetIdList = res[4].object

        // 默认选择第一个省的城市
        // if (res[0].length) {
        //   that.province = that.provinceList[0].id
        //   that.getCityList(res[0].id, 0)
        // }

        valid()
      })
      .catch((error) => {
        console.log(error)

        layer.close(loading)
        layer.msg(error || '初始化数据失败', {
          icon: 5
        })
      })

  },
  watch: {
    province: function (val, oldVal) {
      this.getCityList(val, _.findIndex(this.provinceList, (item) => (item.id === this.province)))
    },
    cityList: function (val, oldVal) {
      // 默认显示第一条数据
      if (val.length) {
        this.city = val[0].id
      }
    }
  },
  methods: {
    // 获取省列表
    getProvinceList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getProvinceList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            reject()
          })
          .always(function () {
          })

      })
    ),
    // 获取城市列表
    getCityList: function (id, index) {
      let that = this

      // 检测index有效性
      if (!(/^\d+$/.test(index)) && index < 0) {
        return
      }

      // 如果已请求过数据则直接读取缓存的数据
      if (this.provinceList[index].cityList) {
        that.cityList = this.provinceList[index].cityList
        return
      }

      let loading = layer.msg('获取数据中...', {
        icon: 16,
        time: 0
      })

      $.ajax({
        url: base + getCityList,
        headers: header,
        data: {
          provinceId: id || 1
        }
      })
        .done(function (res) {
          if (res.code === 0) {
            // 缓存数据到省市列表里
            that.cityList = that.provinceList[index].cityList = res.object
            return
          }

          layer.msg('初始化数据失败', {
            icon: 5
          })
        })
        .fail(function () {
          layer.msg('初始化数据失败', {
            icon: 5
          })
        })
        .always(function () {
          layer.close(loading)
        })
    },
    // 获取开发商列表
    getDeveloper: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getDeveloperList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })

    ),
    // 获取渠道商列表
    getPaychannelList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getPaychannelList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })

    ),
    // 获取告知书模版列表
    getInformBookTemplateList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          url: base + getInformBookTemplateList,
          headers: header
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })

    ),
    // 获取服务类型列表
    getServiceTypeList: () => (
      new Promise((resolve, reject) => {

        $.ajax({
          type: 'POST',
          url: base + getServiceType,
          headers: header,
          data:{
            oneServiceType: ''
          }
        })
          .done(function (res) {
            if (res.code === 0) {
              resolve(res)
            }
            reject(res.message)
          })
          .fail(function () {
            console.log("error")
            reject()
          })
          .always(function () {
          })

      })

    ),
    // 获取二类服务类型列表
    getOtherServiceTypeList: (oneServiceType) => {

      let loading = layer.msg('获取数据中...', {
        icon: 16,
        time: 0
      })

      form.otherServiceType = [];
      form.otherServiceTypeList = [];

      $.ajax({
        type: 'POST',
        url: base + getServiceType,
        headers: header,
        data:{
          oneServiceType: oneServiceType
        }
      })
        .done(function (res) {
          console.log('获取其它服务类型成功')
          console.log(res)

          if (res.code === 0) {
            form.otherServiceTypeList = res.object;
          }
        })
        .fail(function () {
          console.log("error")

          layer.msg('获取其它服务类型失败...', {
            icon: 5,
            time: 0
          })
        })
        .always(function () {
          layer.close(loading);
        })

    },
    // 初始化地图
    initMap: function () {

      let that = this

      let map = new AMap.Map(this.$refs['map-preivew'], {
        resizeEnable: true,
        zoom: 13
      })

      AMap.plugin('AMap.Geocoder', () => {
        let geocoder = new AMap.Geocoder()

        let marker = new AMap.Marker({
          map: map,
          bubble: true
        })

        map.on('click', (e) => {

          marker.setPosition(e.lnglat)

          geocoder.getAddress(e.lnglat, (status, result) => {
            console.log(result);
            console.log(that.province);
            if (status === 'complete') {
              that.propertyAddress = result.regeocode.formattedAddress;
              that.longitude = e.lnglat.lng
              that.latitude = e.lnglat.lat
            }
          })
        })

      })

    },
    // 初始化时间选择
    initTime: function () {
      let that = this

      $(this.$refs.time)
        .datetimepicker({
          autoclose: true,
          todayBtn: true,
          todayHighlight: true,
          format: "yyyy-mm-dd",
          startView: 3,
          minView: 2
        })
        .on('changeDate', function (e) {

          that.openQuotationTime = $(e.target).val()

        })
    },
    // 锁屏图片上传
    uploadLockImg: function () {

      let that = this,
        file = this.$refs.lockImg.files[0]

      if (!file) {
        layer.msg('没有选择文件', {
          icon: 5
        })

        return
      }

      // 检验文件类型
      let allowExt = ['jpg', 'jpeg', 'png'],
        ext = file.name.substr(file.name.lastIndexOf('.') + 1)

      if (_.indexOf(allowExt, ext) === -1) {
        layer.msg('文件格式错误,图片格式只能为' + allowExt.toString(), {
          icon: 5
        })

        return
      }

      // 图片大小校验
      let allowWH = new Promise((resolve, reject) => {
        let allowMinWidth = 1280,
          allowMinHeight = 1080,
          oFReader = new FileReader()

        oFReader.readAsDataURL(file)

        oFReader.onload = function (e) {
          let img = new Image()

          img.onload = function () {
            console.log()
            if (img.width < allowMinWidth || img.height < allowMinHeight) {
              reject('图片太小了' + (img.width < allowMinWidth ? ',当前图片宽度为' + img.width + 'px, 允许的最小宽度为' + allowMinWidth + 'px' : '') + (img.height < allowMinHeight ? ',当前图片高度为' + img.height + 'px, 允许的最小高度为' + allowMinHeight + 'px' : ''))
            } else {
              resolve()
            }

          }

          img.onerror = function (e) {
            reject('图片加载异常')
          }

          img.src = e.target.result

        }
      })

      allowWH.then(function () {
        // 文件名称 时间戳 + 6位随机码
        let key = new Date().getTime().toString() + random_string(6) + get_suffix(file.name)

        that.islockImgLock = true

        let client = new OSS.Wrapper({
          secure: true,
          region: aliyun.region,
          accessKeyId: aliyun.accessKeyId,
          accessKeySecret: aliyun.accessKeySecret,
          bucket: aliyun.bucket
        })

        client.multipartUpload(key, file, {
          progress: function (p) {
            return function (done) {
              that.lockImgProgress = Math.floor(p * 100)
              done()
            }
          }
        }).then(function (res) {
          console.log(res)
          that.lockImg = key
          that.islockImgLock = false
          that.lockImgProgress = 0
          that.lockImgPreview = previewImg(key, {
            'process': 'image/resize,w_350'
          })

          layer.msg('上传锁屏图片成功', {
            icon: 6
          })

        }).catch(function (err) {
          console.log(err)
          that.islockImgLock = false
          that.lockImgProgress = 0

          layer.msg('上传锁屏图片失败', {
            icon: 5
          })

        })

      }).catch(function (error) {
        layer.msg(error || '图片异常', {
          icon: 5,
          time: 8000
        })
      })

    },
    imgPreviewModal: imgPreviewModal,
    clearImgPreview: function (e) {
      this.lockImgPreview = ''
      this.lockImg = ''
      this.$refs.lockImg.val = ''
    }
  }
})

function valid() {

  let form_valid,
    $form = $('#form')

  $.validator.setDefaults({ // 只能放在validate规则配置之前

    // 提交事件
    submitHandler: () => {
      console.log('submit!')

      let loading_modal = layer.msg('提交中...', {
        icon: 16,
        time: 0
      })

      form.isLock = true

      $.ajax({
        url: base + addOrModifyBuildinginfo,
        type: 'POST',
        headers: header,
        contentType: 'application/json',
        data: JSON.stringify({
          buildingInfo: {
            // 是否显示认购协议
            agreement: form.serviceType === 'xf' ? form.agreement : undefined,
            // 楼盘名称
            propertyName: form.propertyName,
            // 楼盘地址
            propertyAddress: form.propertyAddress,
            // 楼盘区域
            propertyArea: form.propertyArea,
            // 省code
            province: form.province,
            // 市code
            city: form.city,
            // 经度
            longitude: form.longitude,
            // 纬度
            latitude: form.latitude,
            // 开发商ID
            dId: form.dId,
            // 开发商ID
            developerName: _.find(form.developerList, (item) => (item.idStr === form.dId)).enterInfo.enterpriseName,
            // 是否全民经纪人可看
            broker: form.broker,
            /*       // 是否查询征信报告
            isCheckZxbg: form.isCheckZxbg,
            // 是否付款给开发商
            isPayToDev: form.isPayToDev,*/
            // 是否创建测试户型
            isCreateTestType: form.isCreateTestType,
            // 是否锁屏
            isLock: form.isQuickLock,
            // 是否POS小票签名
            posSignature: form.posSignature,
            // 是否显示楼盘名称
            isShowName: form.isShowName,
            // 是否显示银行相关信息
            showBankInfo: form.showBankInfo,
            // 是否在公众号展示
            isView: form.isView,
            // 是否签名
            isSignature: form.isSignature,
            // 独立经纪人佣金模式
            brokerCommModel: form.brokerCommModel,
            // 独立经纪人佣金配置
            brokerCommConfig: form.brokerCommConfig,
            // 职业顾问佣金模式
            careerCounselorModel: form.careerCounselorModel,
            // 职业顾问佣金配置
            careerCounselorConfig: form.careerCounselorConfig,
            // 一体机支付渠道配置
            channel: form.channel.join(','),
            // 锁屏图片OSS
            lockImg: form.lockImg,
            // 锁定时间
            lockTime: form.lockTime,
            // 开盘时间
            openQuotationTime: form.openQuotationTime,
            // 负责人联系方式
            picMobile: form.picMobile,
            // 负责人姓名
            picName: form.picName,
            // 告知书打印次数
            printNum: form.printNum,
            //银联小票打印次数
            ylTicketCount: form.ylTicketCount,
            // 售房电话（多个用逗号隔开）
            salePhone: form.salePhone,
            // 服务类型
            serviceType: form.serviceType,
            // 其它服务类型
            otherServiceType: form.otherServiceType.join(','),
            // 告知书模板id
            templetId: form.templetId
          },
          buildingInfoFileModel: {}
        })
      })
        .done(function (res) {
          console.log(res)

          if (res.code === -1) {
            layer.msg(res.message, {
              icon: 5
            })

            form.isLock = false

            return
          }

          layer.msg(`${action}${ title }成功`, {
            icon: 6
          })

          console.log(form.otherServiceType)

          // 重置表单
          $.extend(form.$data, form.$options.data())

          setTimeout(() => {
            window.location = './index.html'
          }, 1000)
        })
        .fail(function (res) {
          console.log(res)

          layer.msg(`${action}${ title }失败`, {
            icon: 5
          })

          console.log("error");
        })
        .always(function (res) {

          layer.close(loading_modal)
          form.isLock = false

        })

    }
  })

  // 验证
  form_valid = $form.validate({
    errorPlacement: function (error, element) {
      element.parents('.col-sm-12').length ? error.appendTo(element.parents('.col-sm-12')) : error.appendTo(element.parents('.col-xs-24'))
    },
    rules: {
      propertyName:  {
        required: true
      },
      dId: {
        required: true
      },
      province: {
        required: true
      },
      city: {
        required: true
      },
      propertyAddress: {
        required: true
      },
      longitude: {
        required: true
      },
      latitude: {
        required: true
      },
      picName: valid_name,
      picMobile: {
        required: true
      },
      openQuotationTime: {
        required: true
      },
      serviceType: {
        required: true
      },
      channel: {
        required: true
      },
      broker: {
        required: true
      },
      isShowName: {
        required: true
      },
      showBankInfo: {
        required: true
      },
/*      isCheckZxbg: {
        required: true
      },
      isPayToDev: {
        required: true
      },*/
      isCreateTestType: {
        required: true
      },
      careerCounselorModel: {
        required: true
      },
      careerCounselorConfig: valid_price,
      brokerCommModel: {
        required: true
      },
      brokerCommConfig: valid_price,
      isView: {
        required: true
      },
      posSignature: {
        required: true
      },
      printNum: {
        required: true
      },
      ylTicketCount: {
        required: true
      },
      lockTime: {
        required: true
      },
      lockImg: {
        required: true
      }
    }
  })

}